#define _CRT_SECURE_NO_WARNINGS 1

//https://leetcode.cn/problems/path-with-maximum-gold/

class Solution {
    int ret = 0;
    bool check[16][16];
    int m, n;
public:
    int getMaximumGold(vector<vector<int>>& grid) {
        m = grid.size(), n = grid[0].size();
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (grid[i][j] != 0)
                {
                    check[i][j] = true;
                    dfs(grid, i, j, grid[i][j]);
                    check[i][j] = false;
                }
            }
        }
        return ret;
    }

    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    void dfs(vector<vector<int>>& grid, int i, int j, int sum)
    {
        ret = max(ret, sum);
        for (int z = 0; z < 4; z++)
        {
            int x = dx[z] + i, y = dy[z] + j;
            if (x >= 0 && x < m && y >= 0 && y < n && !check[x][y] && grid[x][y] != 0)
            {
                check[x][y] = true;
                dfs(grid, x, y, sum + grid[x][y]);
                check[x][y] = false;
            }
        }
    }
};